﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;
using Company.Merchandising.ServiceLayer.EntityManagement.Constants;

namespace Company.Merchandising.ServiceLayer.EntityManagement
{
	public class AddressManager : BaseManager
	{
		public AddressManager(MerchModelEntities modelEntities) : base(modelEntities) { }

		public void AddAddress(DTOAddress dtoAddress)
		{
			if (dtoAddress.City == null)
			{
				throw new InvalidOperationException(ExceptionMessages.SelectCityForAddress);
			}

			DACCity dacCity = new DACCity(_modelEntities);
			City city = dacCity.GetCityById(dtoAddress.City.Id);
			if (city == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.CityDoesNotExistAnyMore, dtoAddress.City.Id));
			}

			Address address = new Address();
			address.District = dtoAddress.Disctrict;
			address.Street = dtoAddress.Street;
			address.BuildingNumber = dtoAddress.BuildingNumber;
			address.LocalNumber = dtoAddress.LocalNumber;
			address.City = city;
			_modelEntities.AddObject(address.GetType().Name, address);
			_modelEntities.SaveChanges();
		}

		public void UpdateAddress(DTOAddress dtoAddress)
		{
			if (dtoAddress.City == null)
			{
				throw new InvalidOperationException(ExceptionMessages.SelectCityForAddress);
			}

			DACCity dacCity = new DACCity(_modelEntities);
			City city = dacCity.GetCityById(dtoAddress.City.Id);
			if (city == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.CityDoesNotExistAnyMore, dtoAddress.City.Id));
			}

			DACAddress dacAddress = new DACAddress(_modelEntities);
			Address address = dacAddress.GetAddressById(dtoAddress.Id);
			if (address == null)
			{
				throw new InvalidOperationException(ExceptionMessages.AddressDoesNotExistAnyMore);
			}

			address.District = dtoAddress.Disctrict;
			address.Street = dtoAddress.Street;
			address.BuildingNumber = dtoAddress.BuildingNumber;
			address.LocalNumber = dtoAddress.LocalNumber;
			address.City = city;
			_modelEntities.SaveChanges();
		}

		public void DeleteAddress(int addressId)
		{
			DACAddress dacAddress = new DACAddress(_modelEntities);
			Address address = dacAddress.GetAddressById(addressId);
			if (address == null)
			{
				throw new InvalidOperationException(ExceptionMessages.AddressDoesNotExistAnyMore);
			}

			if (!address.Locations.IsLoaded)
			{
				address.Locations.Load();
			}

			if (address.Locations.Count > 0)
			{
				throw new InvalidOperationException(ExceptionMessages.AddressPossessesLocations);
			}

			_modelEntities.DeleteObject(address);
			_modelEntities.SaveChanges();
		}
	}
}
